package com.vote.www.controller;

import com.vote.www.core.StaticMap;
import com.vote.www.domain.vo.AccessToken;
import com.vote.www.service.RecommendpicService;
import com.vote.www.service.WeixininfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;


/**
 * Created by 汤伟杰 on 2017/5/8.
 */
@Controller
@RequestMapping("/weixin")
public class WeixinController extends BaseController{

    @Autowired
    private WeixininfoService weixininfoService;
   @Autowired
    private RecommendpicService recommendpicService;

    /**
     * 首页响应
     * @param request
     * @param resp
     * @param model
     * @return
     * @throws IOException
     */
    @RequestMapping("returnUrl.do")
    public String returnUrl(HttpServletRequest request, HttpServletResponse resp,
                        ModelMap model) throws IOException {
        String basePath = request.getRequestURL().substring(0,request.getRequestURL().lastIndexOf(request.getRequestURI()));
        basePath+=request.getContextPath()+"/index.html?access_type=1";
        String encode = getURLEncoderString(basePath);
        encode = encode.toLowerCase();
//        String url =  "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+StaticMap.appid+"&redirect_uri="+encode+"%3facc=1&response_type=code&scope=snsapi_userinfo#wechat_redirect";
//        resp.sendRedirect(url);
        model.addAttribute("url",encode);
        model.addAttribute("appid",StaticMap.appid);
        return "weixinLogin";

    }

    /**
     * 获取微信分享信息
     * @param url
     * @param req
     * @param resp
     * @param model
     * @throws IOException
     */
    @RequestMapping("getInfo.do")
    public void getInfo(@RequestParam(required = true) String url,
                        HttpServletRequest req, HttpServletResponse resp,
                        ModelMap model) throws IOException {
        try {
            if(StaticMap.getAccessToken()==null){
                StaticMap.setAccessToken(new AccessToken());
            }
            AccessToken accessToken = StaticMap.getAccessToken();
            if(accessToken.getEndtime()==null||accessToken.getEndtime()<=System.currentTimeMillis()-60*1000){
                String token = weixininfoService.getAccessToken();
                String ticket = weixininfoService.getTicket(token);
                accessToken.setAccess_token(token);
                accessToken.setTicket(ticket);
            }

            Map<String, String> map = weixininfoService.sign(accessToken.getTicket(), url);
//            System.out.println(JSONObject.toJSONString(map));
            jsonResult(1,"","",map,resp);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult(0,"00","出错："+e.getMessage(),"",resp);
        }
    }
    /**
     * URL 转码
     *
     * @return String
     * @author lifq
     * @date 2015-3-17 下午04:10:28
     */
    public static String getURLEncoderString(String str) {
        String result = "";
        if (null == str) {
            return "";
        }
        try {
            result = java.net.URLEncoder.encode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取微信用户信息
     * @param code
     * @param req
     * @param resp
     * @param model
     * @throws Exception
     */
//    @RequestMapping("getWeixinInfo.do")
    public void getOpenId(@RequestParam(required = true) String code,
                        HttpServletRequest req, HttpServletResponse resp,
                        ModelMap model) throws Exception {

        try {
            jsonResult(1,"","",weixininfoService.getWeixinInfo(code),resp);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult(0,"","获取微信信息出错！"+e.getMessage(),"",resp);
        }


    }


    /**
     * 得到用户基本信息(包括是否关注公众号)
     * @param code
     * @param req
     * @param resp
     * @param model
     */
//    @RequestMapping("getWeixinInfoGzh.do")
    public void getUserInfo(@RequestParam(required = true) String code,
                            HttpServletRequest req, HttpServletResponse resp,
                            ModelMap model){
        try {
//            WeixinInfo weixininfo = recommendpicService.getWeixinUserinfo(code);//得到微信用户信息
//            AccessOpenId openIdEntity = StaticMap.getAccessOpenIdMap(code);
            Map<String,Object> map = weixininfoService.getWeixinGongzhonghao(code);
            jsonResult(1,"","",map,resp);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult(0,"99",e.getMessage(),"",resp);
        }
    }



}
